﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace server.app.table
{
    public class Player : Table<comm.objst.TablePlayer>
    {
        public int AllPlayerCount { get { return Orm.Count(); } }

        public Player(World world)
            : base(Conf.TABLE_NAME_PREFIX + typeof(Player).Name, world)
        {
        }

        bool NicknameExists(SQLx sqlx, string nickname, string ignoreUserId = null)
        {
            var where = SQLx.FormatWhere(new Dictionary<string, object> { 
                {"["+comm.objst.TablePlayer.NICKNAME+"]",nickname},
                {"["+comm.objst.TablePlayer.USER_ID+"]<>",ignoreUserId}
            });
            return (int)sqlx.ExecuteScalar("select count(*) from [" + _tableName + "] " + where.AllText, where.AllArgs) > 0;
        }

        public bool NicknameExists(string nicknick, string ignoreUserId = null)
        {
            return _world.DataManager.Call<bool>(sqlx =>
            {
                return NicknameExists(sqlx, nicknick, ignoreUserId);
            });
        }
        public comm.objst.TablePlayer GetPlayer(string playerId)
        {
            return Orm.GetObjectByKey(playerId);
        }
        public comm.objst.TablePlayer[] GetAllPlayer(string userId)
        {
            var where = SQLx.FormatWhere(new Dictionary<string, object>{
                {"["+comm.objst.TablePlayer.USER_ID+"]",userId}
            });
            return Orm.GetList("select * from [" + _tableName + "] " + where.AllText + " order by [" + comm.objst.TablePlayer.ROW_CREATE_TIME + "] asc", where.AllArgs);
        }
        public bool UpdatePlayer(comm.objst.TablePlayer tablePlayer)
        {
            return Orm.Update(tablePlayer);
        }
        public bool CreatePlayer(SQLx sqlx, comm.objst.TablePlayer tablePlayer)
        {
            return Orm.Insert(sqlx, tablePlayer);
        }
    }
}
